<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;


/**
 * 文旅打卡作品投票模型
 * Class ArticleTypeModel
 * @package app\common\model
 */
class ScenicWorksVote extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;

    protected $table = 'scenic_works_vote';

    /**
     * 判断是否点赞（只能点赞一次）
     * @param scenic_id 景点id
     * @param user_id  用户id
     * @param scenic_works_id 作品id
     */
    public function worksIsVote($user_id,$scenic_id,$scenic_works_id){
        return $this->where('scenic_id' , $scenic_id)->where('user_id' , $user_id)->where('scenic_works_id' , $scenic_works_id)->first();
    }

     /**
     * 点赞和取消点赞
     * @param scenic_id 景点id
     * @param user_id  用户id
     * @param scenic_works_id 作品id
     */
    public function voteAndCancel($user_id,$scenic_id,$scenic_works_id){
        $res = $this->worksIsVote($user_id,$scenic_id,$scenic_works_id);
        if($res){
           $result = $this->where('scenic_id' , $scenic_id)->where('user_id' , $user_id)->where('scenic_works_id' , $scenic_works_id)->delete();
           //减少点赞数
           ScenicWorks::where('scenic_id' , $scenic_id)->where('id' , $scenic_works_id)->decrement('vote_num');

           $msg = '取消点赞';
        }else{
            $this->scenic_id = $scenic_id;
            $this->user_id = $user_id;
            $this->scenic_works_id = $scenic_works_id;
            $result = $this->save();

             //增加点赞数
           ScenicWorks::where('scenic_id' , $scenic_id)->where('id' , $scenic_works_id)->increment('vote_num');

           $msg = '点赞';
        }
        return $msg;
    }


}